package com.tianjishuju.cimiss.station.station.api;

import com.tianjishuju.cimiss.station.station.model.UpDateStreamBean;
import com.tianjishuju.cimiss.station.station.util.ConvertUtil;
import com.tianjishuju.cimiss.station.station.util.HttpUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/DataStream")
public class DataStreamApi {
    private static Logger logger = Logger.getLogger(DataStreamApi.class);
    @Value("${upAndLowdataLV}")
    private String upAndLowdataLV;

    private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH");
    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
    private DecimalFormat doubleFormat = new DecimalFormat("######0.000");
    private List<UpDateStreamBean> list = new ArrayList<>();
    private long timestap;

    private Map<String, Object> send = new HashMap<>();
    private Map<String, Object> save = new HashMap<>();
    private int hourOfDay;//上行数据



    @GetMapping("/getUpdataLV")
    public Map<String, Object> getUpdataLV(@RequestParam("fasong") boolean fasong) {
        synchronized (DataStreamApi.class) {
            String name = "";
            if (fasong) {
                name = "CTS发送";
            } else {
                name = "CTS接收";
            }
            Map<String, Object> rtn = new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            int now = calendar.HOUR_OF_DAY;
            if (now == hourOfDay) {
                if (fasong) {
                    if (send.size()>0)
                    return send;
                } else {
                    if (save.size()>0)
                    return save;
                }
            }
            hourOfDay = now;
            calendar.add(Calendar.HOUR_OF_DAY, -8);
            String time = yyyyMMddHH.format(calendar.getTime()) + "0000";
            calendar.add(Calendar.HOUR_OF_DAY, -1);
            String time1 = yyyyMMddHH.format(calendar.getTime()) + "0000";
            System.out.println(time);
            System.out.println(time1);
            String[] datacodes = {"ST(A)", "ST(A)_WUREN", "ST(R)", "交通站报文", "TURANG", "TIAN"};
            String[] datacodes1 = {"UPAR_GPS", "RADI", "CAWN_PMMUL"};
            try {
                for (String datacode : datacodes) {
                    datacode = URLEncoder.encode(datacode, "utf-8");
                    String url = upAndLowdataLV + "/up/pktDetailUpMonD3.do?msg_code=" + datacode + "&item_time=" + time;
                    //System.out.println(url);
                    Map<String, Object> stringObjectMap = HttpUtil.doPost(url);
                    if (stringObjectMap != null) {
                        Map<String, Object> map = getHttpRtnBodyToMap(stringObjectMap);
                        if (map != null) {
                            for (int i = 0; i < 5; i++) {
                                map = getStringObjectMap(rtn, map, name);
                                if (map == null) break;
                            }
                        }
                    }
                    //Thread.sleep(5000);
                }
                for (String datacode : datacodes1) {
                    datacode = URLEncoder.encode(datacode, "utf-8");
                    String url = upAndLowdataLV + "/up/pktDetailUpMonD3.do?msg_code=" + datacode + "&item_time=" + time1;
                    //System.out.println(url);
                    Map<String, Object> stringObjectMap = HttpUtil.doPost(url);
                    if (stringObjectMap != null) {
                        Map<String, Object> map = getHttpRtnBodyToMap(stringObjectMap);
                        if (map != null) {
                            for (int i = 0; i < 5; i++) {
                                map = getStringObjectMap(rtn, map, name);
                                if (map == null) break;
                            }
                        }
                    }
                    //Thread.sleep(5000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                logger.debug("完成");
                if (fasong) {
                    send = rtn;
                } else {
                    save = rtn;
                }
                return rtn;
            }
        }
    }
    public Map getStringObjectMap(Map<String, Object> save, Map<String, Object> map,String name) {
        List<Map<String, Object>> map1 = (List<Map<String, Object>>) map.get("children");
        if (map1 != null) {
            map = null;
            map = map1.get(0);
            if (name.equals(map.get("name"))) {
                Map<String, Object> moninfo = (Map<String, Object>) map.get("moninfo");
                if (moninfo != null) {
                    int due_num = (int) moninfo.get("due_num");
                    int timely_num = (int) moninfo.get("timely_num");
                    String msg_code = (String) moninfo.get("msg_code");
                    System.out.println(name+"--" + msg_code + "---" + (double) timely_num / due_num);
                    save.put(msg_code, doubleFormat.format((double) timely_num / due_num));
                }
            }

            return map;
        }
        return null;
    }


    @GetMapping("/getLowLV")
    public List<UpDateStreamBean> getLowLV() {
        synchronized (DataStreamApi.class) {
            Calendar calendar = Calendar.getInstance();
            long now = calendar.getTime().getTime();
            if ((now - timestap) < 60 * 60 * 1000 && list.size() == 28) {
                return list;
            }
            String time = yyyyMMdd.format(calendar.getTime());
            System.out.println(calendar.HOUR_OF_DAY);
            String[] ECMWF_THIICK = new String[]{"ECMWF_THIICK_00", "ECMWF_THIICK_12"};
            String[] ECMWF_THIN = new String[]{"ECMWF_THIN_00", "ECMWF_THIN_12"};
            String[] JP_THIICK = new String[]{"JP_THIICK_00", "JP_THIICK_06", "JP_THIICK_12", "JP_THIICK_18"};
            String[] JP_THIN = new String[]{"JP_THIN_00", "JP_THIN_06", "JP_THIN_12", "JP_THIN_18"};
            String[] T639_THIICK = new String[]{"T639_THIICK_00", "T639_THIICK_06", "T639_THIICK_12", "T639_THIICK_18"};
            String[] T639_THIN = new String[]{"T639_THIN_00", "T639_THIN_06", "T639_THIN_12", "T639_THIN_18"};
            String[] kwbc = new String[]{"kwbc_00", "kwbc_12"};
            String[] gerrain = new String[]{"gerrain_00", "gerrain_12"};
            String[] Grapes = new String[]{"Grapes_00", "Grapes_12"};
            String[] GRPAPS_MESO = new String[]{"GRPAPS_MESO_00", "GRPAPS_MESO_12"};
            String[][] datacodess1 = {ECMWF_THIICK, ECMWF_THIN, JP_THIICK, JP_THIN, T639_THIICK, T639_THIN, kwbc, gerrain, Grapes, GRPAPS_MESO};
            try {
                for (int i = 0; i < 10; i++) {
                    downLowlv(list, calendar,time, datacodess1[i]);
                   // downLowlv(list, time1, datacodess1[i]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                logger.info("完成");
                timestap = new Date().getTime();
                return list;
            }
        }
    }
    private void downLowlv(List<UpDateStreamBean> list, Calendar calendar, String time, String[] ECMWF_THIICK) throws Exception {
        int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        Date time2 = calendar.getTime();
        for (String datacode : ECMWF_THIICK) {
            datacode = URLEncoder.encode(datacode, "utf-8");
            String substring = datacode.substring(datacode.length() - 2);
            //00,06,12,18
            int newhour = Integer.valueOf(substring);
            if (newhour > hourOfDay||(hourOfDay-newhour)<12) {
                logger.info("newhour:"+newhour+"---"+"hourOfDay"+hourOfDay);
                calendar.add(Calendar.DAY_OF_MONTH,-1);
                time = yyyyMMdd.format(calendar.getTime());
                calendar.setTime(time2);
            }
            String time1 = time +substring+"0000";
            String url = upAndLowdataLV + "/low/pktDetailLowMonD3.do?msg_code=" + datacode + "&item_time=" + time1;
            System.out.println(url);
            Map<String, Object> stringObjectMap = HttpUtil.doPost(url);
            if (stringObjectMap != null) {
                Map<String, Object> map = getHttpRtnBodyToMap(stringObjectMap);
                if (map != null) {
                    if ("CTS接收".equals(map.get("name"))) {
                        UpDateStreamBean upDateStreamBean = getupDateStreamBean(map);
                        if (upDateStreamBean != null) {
                            list.add(upDateStreamBean);
                        }
                    } else {
                        List<Map<String, Object>> children = (List<Map<String, Object>>) map.get("children");
                        Map<String, Object> map1 = children.get(0);
                        UpDateStreamBean upDateStreamBean = getupDateStreamBean(map1);
                        if (upDateStreamBean != null) {
                            list.add(upDateStreamBean);
                        }
                    }

                }
            }
        }
        Thread.sleep(500);
    }

    private UpDateStreamBean getupDateStreamBean(Map<String, Object> map) {
        UpDateStreamBean upDateStreamBean = new UpDateStreamBean();
        Map<String, Object> moninfo = (Map<String, Object>) map.get("moninfo");
        if (moninfo != null) {
            int timely_num = (int) moninfo.get("timely_num");
            upDateStreamBean.setCount(timely_num);
            long due_time = (long) moninfo.get("due_time");
            upDateStreamBean.setTime(due_time);
            String msg_type = (String) moninfo.get("msg_type");
            upDateStreamBean.setMsg_type(msg_type);
            String msg_code = (String) moninfo.get("msg_code");
            upDateStreamBean.setMsg_code(msg_code);
            return upDateStreamBean;
        }
        return null;
    }



    @GetMapping("/getAllDayCount")
    public List<Map<String,Object>> getAllDayCount(){
        List<Map<String,Object>> rtn = new ArrayList<>();
        Map<String,Object> map =new HashMap<>();
        if (list.size()==0){
            getLowLV();
        }
        for (UpDateStreamBean upDateStreamBean : list) {
            if (map.get(upDateStreamBean.getMsg_type())!=null){
                map.put(upDateStreamBean.getMsg_type(),upDateStreamBean.getCount()+(int)map.get(upDateStreamBean.getMsg_type()));
            }else map.put(upDateStreamBean.getMsg_type(),upDateStreamBean.getCount());
        }
        rtn.add(map);
        return rtn;
    }

    public Map getHttpRtnBodyToMap(Map<String, Object> map1) {
        byte[] bytes = (byte[]) map1.get("content");
        Map map = null;
        try {
            String res = new String(bytes, "UTF-8");
            return ConvertUtil.jsonStrToObject(res, Map.class);
        } catch (Exception e) {
            logger.error("解析http body出现错误", e);
            return null;
        }
    }

}
